import getShortcutByName from "./api/getShortcutByName";
import putShortcutViewstates from "./api/putShortcutViewstates";
import updateShortcutViewstate from "./api/updateShortcutViewstate";

const fetchViewstateFromSlash = async(name: string) => {
  console.log("fetch viewstates from slash...");
  // const name = "786b8c9a876033576a156c6ce88c2b59a0e394fd";
  const response = await getShortcutByName(name);
  const shortcut = response.shortcut;
  if (!shortcut.comments || shortcut.comments.trim() === "") return;
  const highlightViewstates = shortcut.comments.trim().split("\n\n");
  return highlightViewstates;
}

const storeViewstateToSlash = async (name: string, viewstate: string) => {
  try {
    await updateShortcutViewstate(name, viewstate);
    console.log("store viewstate to slash successfully.");
  } catch (error) {
    console.error(`store viewstate to slash failed: ${error}`);
    throw error;
  }
}

const removeViewstateFromSlash = async (name: string, highlightId: string) => {
  const data = await getShortcutByName(name);
  const shortcut = data.shortcut;
  if (!shortcut.comments || shortcut.comments.trim() === "") return;
  let highlightViewstates = shortcut.comments.trim().split("\n\n");
  highlightViewstates = highlightViewstates.filter(item => {
    return item.indexOf(highlightId) === -1;
  });
  const viewstates = highlightViewstates.join("\n\n");
  try {
    await putShortcutViewstates(name, viewstates);
    console.log("remove viewstate from slash successfully.");
  } catch (error) {
    console.error(`remove viewstate from slash failed: ${error}`);
    throw error;
  }
}

const clearViewstateFromSlash = async (name: string)=> {
  console.warn("unimplemented!");
}

export {
  fetchViewstateFromSlash,
  storeViewstateToSlash,
  removeViewstateFromSlash,
  clearViewstateFromSlash
}
